package demo

import (
	"bufio"
	"io"
	"net"
)

// pkg/conn/connection.go
package conn

import (
"bufio"
"io"
"net"
"tcp-lib/pkg/codec"
"tcp-lib/pkg/router"
)

const (
	maxPacketSize = 10 * 1024 * 1024 // 10MB最大包限制
)

type TCPConn struct {
	net.Conn
	Codec   *codec.LengthHeaderCodec
	Router  *router.Router
	Session Session
	reader  *bufio.Reader
}

func NewTCPConn(c net.Conn, codec *codec.LengthHeaderCodec, router *router.Router) *TCPConn {
	return &TCPConn{
		Conn:    c,
		Codec:   codec,
		Router:  router,
		reader:  bufio.NewReaderSize(c, 4096), // 使用带缓冲的reader
		Session: NewSession(),
	}
}

func (c *TCPConn) Process() error {
	for {
		protocolID, msg, err := c.Codec.Decode(c.reader)
		if err != nil {
			if err == io.EOF {
				return nil
			}
			if err == codec.ErrIncompletePacket {
				continue
			}
			return err
		}

		if handler, ok := c.Router.GetHandler(protocolID); ok {
			go handler(c, msg) // 带连接上下文的处理
		}
	}
}

// 发送消息封装
func (c *TCPConn) Send(protocolID uint32, msg proto.Message) error {
	data, err := c.Codec.Encode(protocolID, msg)
	if err != nil {
		return err
	}

	_, err = c.Conn.Write(data)
	return err
}